package com.cby.code.net;

import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: RequestParam
 * @author: ChenBaoYang
 * @createDate: 2022/1/18 10:06 下午
 */
public class RequestParam {

    private static final String QUESTION_SYMBOL = "?";

    private static final String EQUAL_SIGN_SYMBOL = "=";

    private static final String AND_SYMBOL = "&";

    /** 请求参数 */
    private Map<String, Object> param = new HashMap<>();
    /** 请求的header */
    private List<Header> headers = new ArrayList<>();

    protected RequestParam(Builder builder) {
        this.param = builder.param;
        this.headers = builder.headers;
    }

    /**
     * 将参数集合转成拼接好的接口地址的后缀
     */
    public String convertToPathParamString() {
        return QUESTION_SYMBOL+convertParamString();
    }

    /**
     * 将参数集合进行拼接
     */
    public String convertParamString() {
        StringBuilder paramSB = new StringBuilder();
        boolean isFirst = true;
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            if(isFirst) {
                isFirst = false;
            } else {
                paramSB.append(AND_SYMBOL);
            }
            paramSB.append(entry.getKey())
                    .append(EQUAL_SIGN_SYMBOL)
                    .append(URLEncoder.encode(String.valueOf(entry.getValue())));
        }
        return paramSB.toString();
    }

    public Map<String, Object> getParam() {
        return param;
    }

    /**
     * 设置http请求头
     */
    public void putHeaders(HttpURLConnection urlConnection) {
        if(headers != null && !headers.isEmpty() && urlConnection != null) {

            for (Header header : headers) {
                urlConnection.setRequestProperty(header.getName(), header.getValue());
            }
        }
    }


    public static class Builder{

        Map<String, Object> param = new HashMap<>();

        List<Header> headers = new ArrayList<>();

        public Builder addParam(String key, Object value) {
            param.put(key, value);
            return this;
        }

        public Builder addHeader(String key, String value) {
            headers.add(new Header(key, value));
            return this;
        }

        public RequestParam build(){
            return new RequestParam(this);
        }

    }
}
